package req

import (
	"errors"
	"fmt"
	"gopkg.in/h2non/gentleman.v2"
	"gopkg.in/h2non/gentleman.v2/plugins/body"
	"gopkg.in/h2non/gentleman.v2/plugins/bodytype"
)

func PostUrlencoded(url string, params map[string]string) string {
	cli := gentleman.New()
	cli.URL(url)
	req := cli.Request()
	req.Method("POST")

	req.Use(body.JSON(params))
	req.Use(bodytype.Type("urlencoded"))

	res, err := req.Send()
	if err != nil {
		fmt.Printf("Request error: %s\n", err)
		return ""
	}
	if !res.Ok {
		fmt.Printf("Invalid server response: %d\n", res.StatusCode)
		return ""
	}

	return res.String()
}

func PostJson(url string, params map[string]interface{}) (string, error) {
	cli := gentleman.New()
	cli.URL(url)
	req := cli.Request()
	req.Method("POST")
	req.Use(body.JSON(params))
	res, err := req.Send()
	if err != nil {
		fmt.Printf("Request error: %s\n", err)
		return "", err
	}
	if !res.Ok {
		fmt.Printf("Invalid server response: %d\n", res.StatusCode)
		return "", errors.New("请求异常")
	}
	return res.String(), nil
}

func Get(url string) (string, error) {
	cli := gentleman.New()
	cli.URL(url)
	req := cli.Request()
	req.Method("GET")
	res, err := req.Send()
	if err != nil {
		fmt.Printf("Request error: %s\n", err)
		return "", err
	}
	if !res.Ok {
		fmt.Printf("Invalid server response: %d\n", res.StatusCode)
		return "", errors.New("请求异常")
	}
	return res.String(), nil
}
